//
//  ZDoctorReplyViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/15.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZDoctorReplyViewController.h"
#import "ZDoctorReplyTableViewCell.h"
#import "ZReplyDetailedViewController.h"
#import "ZValuationViewController.h"
#import "ZOnceSubmitViewController.h"
#import "ZLookFriendDeatilViewController.h"
#import "SPVoiceManager.h"
#import "DoctorReplyModel.h"
#import "PersonInfoModel.h"
#import "SPPlaceholderCell.h"
static NSString *const placeCellID = @"placeholders";

static NSString * const KZDoctorReplyIdentifier = @"KZDoctorReplyIdentifier";
static int _page = 1;
@interface ZDoctorReplyViewController () <UITableViewDelegate,UITableViewDataSource,OnceSubDelegate>{
    LZUserInfo *userInfo;
}
@property (nonatomic,strong) UITableView * mainTableView;
@property (nonatomic,strong) UIImageView *  GUESSimageView; // 暂无内容占位图
@property (nonatomic,assign) BOOL isHaveData;


/** 医生回复个人信息模型数组 */
@property (nonatomic, strong) NSMutableArray <PersonInfoModel *> *personItemArr;

/** 医生回复模型数组 */
@property (nonatomic, strong) NSMutableArray <DoctorReplyModel *> *doctorReplyArr;


@end

@implementation ZDoctorReplyViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([[SPVoiceManager defaultManager] isPlaying]) {
        [[SPVoiceManager defaultManager] stop];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    userInfo = [LZUserInfo getUserInfo];
    _doctorReplyArr = [NSMutableArray array];
    _personItemArr = [NSMutableArray array];
    // Do any additional setup after loading the view.
    [self initialzeDatas];
    [self initlizeInterface];
    [_mainTableView.mj_header beginRefreshing];
}
- (void)initialzeDatas {
    self.isHaveData = YES;
}
- (void)initlizeInterface {
    self.navigationItem.title = @"医生回复";
    self.view.backgroundColor = MYGRAYCOLOR;
    [self.view addSubview:self.mainTableView];
//    [self.view addSubview:self.GUESSimageView];
}
// 表格视图协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.isHaveData == YES ? self.doctorReplyArr.count : 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == YES) {
        ZDoctorReplyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KZDoctorReplyIdentifier forIndexPath:indexPath];
        
        cell.doctorReplyModel = _doctorReplyArr[indexPath.row];
        cell.personInfoModel = _personItemArr[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        SPPlaceholderCell *cell = [tableView dequeueReusableCellWithIdentifier:placeCellID];
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == YES) {
        return 160*ysIZE;
    }else {
        return  SCREEN_Height-104;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == NO) {
        return;
    }
    DoctorReplyModel * model = _doctorReplyArr[indexPath.row];
    model.is_read = @"1";
    PersonInfoModel * pmodel = _personItemArr[indexPath.row];
    [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    if ([model.status isEqualToString:@"1"]) {
        ZOnceSubmitViewController * ZOSVC =[[ZOnceSubmitViewController alloc] init];
        ZOSVC.oPersonModel = pmodel;
        ZOSVC.onceDelegate = self;
        ZOSVC.qId = model.pid;
        ZOSVC.ishiden = YES;
        [self.navigationController pushViewController:ZOSVC animated:YES];
    }else if ([model.status isEqualToString:@"2"]){
        ZReplyDetailedViewController * ZRDVC = [[ZReplyDetailedViewController alloc] init];
                ZRDVC.qId = model.pid;
                ZRDVC.personModel = pmodel;
                [self.navigationController pushViewController:ZRDVC animated:YES];
    }else if ([model.status isEqualToString:@"3"]) {
        ZValuationViewController * zvVC = [[ZValuationViewController alloc] init];
        zvVC.qId = model.pid;
        zvVC.personModel = pmodel;
        zvVC.ishiden = YES;
        [self.navigationController pushViewController:zvVC animated:YES];
    }else {
        ZLookFriendDeatilViewController * zlVC = [[ZLookFriendDeatilViewController alloc] init];
        zlVC.qId = model.pid;
        zlVC.ishiden = YES;
        [self.navigationController pushViewController:zlVC animated:YES];
    }
//    }else if ([model.status isEqualToString:@"2"]) {
//        ZReplyDetailedViewController * ZRDVC = [[ZReplyDetailedViewController alloc] init];
//        ZRDVC.qId = model.pid;
//        ZRDVC.personModel = pmodel;
//        [self.navigationController pushViewController:ZRDVC animated:YES];
//    }
    
}

- (void)refurbish {
    [self.mainTableView.mj_header beginRefreshing];
}

// lazy
- (UITableView *)mainTableView {
    if (_mainTableView) {
        return _mainTableView;
    }
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, 502*ysIZE) style:UITableViewStylePlain];
    _mainTableView.dataSource = self;
    _mainTableView.delegate = self;
//    _mainTableView.rowHeight = 160 *ysIZE;
    _mainTableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    [_mainTableView registerClass:[ZDoctorReplyTableViewCell class] forCellReuseIdentifier:KZDoctorReplyIdentifier];
    [_mainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([SPPlaceholderCell class]) bundle:nil] forCellReuseIdentifier:placeCellID];
    // 下拉刷新
    __weak typeof(self) weakSelf = self;
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownData];
        [_mainTableView.mj_header endRefreshing];
    }];
    // 上拉加载
    _mainTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
        [_mainTableView.mj_footer endRefreshing];
    }];
    
    
    return _mainTableView;
}
- (UIImageView *)GUESSimageView {
    if (_GUESSimageView) {
        return _GUESSimageView;
    }
    _GUESSimageView = [[UIImageView alloc] initWithFrame:CGRectMake(110*xsIZE, 150*ysIZE, 100*xsIZE, 130*ysIZE)];
    _GUESSimageView.image = [UIImage imageNamed:@"reply_none"];
    return _GUESSimageView;
}

// 下拉刷新方法
- (void)pullDownData {
    _page = 1;
    [YJProgressHUD  showProgress:@"正在刷新" inView:self.view];
    NSDictionary *paramas = @{@"p":[NSString stringWithFormat:@"%d",_page],@"uid":userInfo.uid};
    __weak typeof(self) weakSelf = self;
    self.isHaveData = YES;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Index/answerList" sucessBlock:^(id content) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [weakSelf dealPullDownDataWithDict:dict];
        }else {
            self.isHaveData = NO;
            [self.mainTableView reloadData];
            [YJProgressHUD showProgress:@"加载失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        self.isHaveData = NO;
        [self.mainTableView reloadData];
        [YJProgressHUD showMessage:@"网络请求失败" inView:self.view];
    }];
}

// 上啦加载方法
- (void)loadMoreData {
    _page ++;
    NSDictionary *paramas = @{@"p":[NSString stringWithFormat:@"%d",_page],@"uid":userInfo.uid};
    __weak typeof(self) weakSelf = self;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Index/answerList" sucessBlock:^(id content) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [weakSelf dealPullUpDataWithDict:dict];
        }else {
            [YJProgressHUD showMessage:@"记载失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"加载失败" inView:self.view];
    }];
    
}

// 处理下拉刷新数据
- (void)dealPullDownDataWithDict:(NSDictionary *)dict {
    [self.mainTableView.mj_footer resetNoMoreData];
    [_doctorReplyArr removeAllObjects];
    [_personItemArr removeAllObjects];
    
    NSArray *tempArr = dict[@"list"];
    if (tempArr.count == 0) {
        self.isHaveData = NO;
        [YJProgressHUD showMessage:@"没有更多数据了~" inView:self.view];
        [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
        
    }else if (tempArr.count < 10) {
        [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
    }
    for (NSDictionary *dict in tempArr) {
        DoctorReplyModel *doctorReplyModel = [[DoctorReplyModel alloc] initWithDict:[dict mutableCopy]];
        [_doctorReplyArr addObject:doctorReplyModel];
        NSMutableDictionary *mutDict = [@{@"time":dict[@"time"],@"icon":userInfo.userIcon,@"name":userInfo.userName} mutableCopy];
        PersonInfoModel *personinfoModel = [[PersonInfoModel alloc] initWithDict:mutDict];
        
        [_personItemArr addObject:personinfoModel];
    }
    [_mainTableView reloadData];
}

// 处理上啦加载数据
- (void)dealPullUpDataWithDict:(NSDictionary *)dict {
    [self.mainTableView.mj_footer resetNoMoreData];
    NSArray *tempArr = dict[@"list"];
    
    if (tempArr.count == 0) {
        [YJProgressHUD showMessage:@"没有更多数据了~" inView:self.view];
        [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
        [self.mainTableView reloadData];
        return;
    }else if (tempArr.count < 10) {
        [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
    }
    for (NSDictionary *dict in tempArr) {
        DoctorReplyModel *doctorReplyModel = [[DoctorReplyModel alloc] initWithDict:[dict mutableCopy]];
        [_doctorReplyArr addObject:doctorReplyModel];
        
        NSMutableDictionary *mutDict = [@{@"time":dict[@"time"],@"icon":userInfo.userIcon,@"name":userInfo.userName} mutableCopy];
        PersonInfoModel *personinfoModel = [[PersonInfoModel alloc] initWithDict:mutDict];
        
        
        [_personItemArr addObject:personinfoModel];
    }
    [_mainTableView reloadData];
}


@end
